<template>
  <TreeTableLayout>
    <template #tree>
      <BaseTree @query="doQuery" />
    </template>
    <template #table>
      <RightTableLayout :slotName="['search', 'operation', 'table', 'pagination']">
        <template #search>
          <Query :columns="columns" @query="doQuery"></Query>
        </template>
        <template #operation>
          <el-button @click="add">
            <el-icon>
              <DocumentAdd />
            </el-icon>{{ i18n.fy.新增 }}</el-button>
        </template>
        <template #table>
          <el-table :empty-text="i18n.fy.nodata" :data="data.tableData" border v-loading="data.loading"
            :element-loading-text="i18n.fy.loading">
            <el-table-column prop="id" label="ID" align="center" />
            <el-table-column prop="pid" :label="i18n.language === 'zh-cn' ? '父节点ID' : 'ParentNodeID'" align="center" />
            <el-table-column prop="title" :label="i18n.language === 'zh-cn' ? '菜单名称' : 'menuname'" align="center" />
            <el-table-column prop="href" :label="i18n.language === 'zh-cn' ? '菜单地址' : 'href'" align="center" />
            <el-table-column prop="target" :label="i18n.language === 'zh-cn' ? '菜单页面' : 'target'" align="center" />
            <el-table-column prop="spread" :label="i18n.language === 'zh-cn' ? '是否展开' : 'spread'" align="center">
              <template #default="scope">
                <a color="blue" v-if="scope.row.spread == '1'">展开</a>
                <a color="red" v-else>不展开</a>
              </template>
            </el-table-column>
            <el-table-column prop="icon" :label="i18n.language === 'zh-cn' ? '菜单图标' : 'icon'" align="center">
              <template #default="scope">
                <div class="layui-icon" v-html="scope.row.icon"></div>
              </template>
            </el-table-column>
            <el-table-column prop="" :label="i18n.language === 'zh-cn' ? '是否可用' : 'Isitavailable'" align="center">
              <template #default="scope">
                <a color="blue" v-if="scope.row.available == '1'">可用</a>
                <a color="red" v-else>不可用</a>
              </template>
            </el-table-column>
            <el-table-column prop="op" :label="i18n.language === 'zh-cn' ? '操作' : 'operate'" align="center">
              <template #default="scope">
                <div v-if="scope.row.pid != 0">
                  <a class="layui-btn layui-btn-xs" @click="edit(scope.row)">
                    {{ i18n.language === "zh-cn" ? "编辑" : "edit" }}
                  </a>
                  <a class="layui-btn layui-btn-danger layui-btn-xs" @click="del(scope.row)">
                    {{ i18n.language === "zh-cn" ? "删除" : "delete" }}
                  </a>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </template>
        <template #pagination>
          <el-pagination @size-change="onChanSize" @current-change="onChanPage"
            v-model:current-page="data.queryForm.page" v-model:page-size="data.queryForm.limit" :total="data.total" />
        </template>
      </RightTableLayout>
    </template>
  </TreeTableLayout>

  <div id="saveOrUpdateDiv" style="display: none; padding: 20px">
    <form class="layui-form" lay-filter="dataFrm" id="dataFrm">
      <div class="layui-form-item">
        <label class="layui-form-label">
          {{ i18n.language === "zh-cn" ? "父级菜单" : "ParentMenu" }}
          :</label>
        <div class="layui-input-block">
          <div class="layui-unselect layui-form-select" id="pid_div">
            <div class="layui-select-title">
              <input type="hidden" name="pid" id="pid" />
              <input type="text" name="pid_str" id="pid_str"
                :placeholder="i18n.language === 'zh-cn' ? '请选择' : 'Please select'" readonly=""
                class="layui-input layui-unselect" />
              <i class="layui-edge"></i>
            </div>
          </div>
          <div class="layui-card select-test" id="menuSelectDiv">
            <div class="layui-card-body">
              <div id="toolbarDiv">
                <ul id="menuTree" class="dtree" data-id="0" style="width: 100%"></ul>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="layui-form-item">
        <label class="layui-form-label">
          {{ i18n.language === "zh-cn" ? "菜单名称" : "menuName" }}
          :</label>
        <div class="layui-input-block">
          <input type="hidden" name="id" />
          <input type="text" name="title"
            :placeholder="i18n.language === 'zh-cn' ? '请输入菜单名称' : 'Please enter a menu name'" autocomplete="off"
            class="layui-input" />
        </div>
      </div>
      <div class="layui-form-item">
        <label class="layui-form-label">
          {{ i18n.language === "zh-cn" ? "菜单地址" : "MenuAddress" }}
          :</label>
        <div class="layui-input-block">
          <input type="text" name="href"
            :placeholder="i18n.language === 'zh-cn' ? '请输入菜单地址' : 'Please enter the menu address'" autocomplete="off"
            class="layui-input" />
        </div>
      </div>
      <div class="layui-form-item">
        <div class="layui-block">
          <label class="layui-form-label">
            {{ i18n.language === "zh-cn" ? "菜单图标" : "MenuIcon" }}
            :</label>
          <div class="layui-input-block">
            <input type="text" name="icon"
              :placeholder="i18n.language === 'zh-cn' ? '请输入菜单图标' : 'Please enter the menu icon'" lay-verify="required"
              autocomplete="off" class="layui-input" />
          </div>
        </div>
      </div>
      <div class="layui-form-item" style="width: 100%">
        <div class="layui-inline">
          <label class="layui-form-label">
            {{ i18n.language === "zh-cn" ? "是否展开" : "Expand or not" }}
            :</label>
          <div class="layui-input-inline">
            <input type="radio" name="spread" value="1" :title="i18n.language === 'zh-cn' ? '展开' : 'expand'" />
            <input type="radio" name="spread" value="0" :title="i18n.language === 'zh-cn' ? '不展开' : 'DoNotExpand'"
              checked="checked" />
          </div>
        </div>
        <div class="layui-inline">
          <label class="layui-form-label">
            {{ i18n.language === "zh-cn" ? "是否可用" : "Is it available" }}
            :</label>
          <div class="layui-input-inline">
            <input type="radio" name="available" value="1" checked="checked"
              :title="i18n.language === 'zh-cn' ? '可用' : 'available'" />
            <input type="radio" name="available" value="0" :title="i18n.language === 'zh-cn' ? '不可' : 'cannot'" />
          </div>
        </div>
      </div>
      <div class="layui-form-item" style="text-align: center; width: 100%">
        <div class="layui-input-block" style="margin-left: 0">
          <button type="button" class="layui-btn layui-btn-normal layui-btn-sm layui-icon layui-icon-release"
            lay-filter="doSubmit" lay-submit="">
            {{ i18n.fy.提交 }}
          </button>
          <button type="reset" class="layui-btn layui-btn-warm layui-btn-sm layui-icon layui-icon-refresh">
            {{ i18n.fy.重置 }}
          </button>
        </div>
      </div>
    </form>
  </div>
</template>

<script setup>
defineOptions({ name: "MenuList" });
import RightTableLayout from "@/views/workbench/components/RightTableLayout.vue";
import TreeTableLayout from "@/views/workbench/components/TreeTableLayout.vue";
import { i18nStore } from "@/pinia/i18n";
const i18n = i18nStore();
import Query from "@/components/query.vue";
import BaseTree from "@/components/baseTree.vue";
const {
  appContext: {
    config: { globalProperties },
  },
} = getCurrentInstance();
let $httpUrl = globalProperties.$httpUrl;

let columns = reactive({ title: { label: "title", queryValue: "" } });

let data = reactive({
  queryForm: {
    page: 1,
    limit: 100,
  },
  tableData: [],
  total: 0,
  dialog: false,
  form: {},
  rules: {
    name: [{ required: true, message: "请输入姓名", trigger: "change" }],
    role: [{ required: true, message: "请选择岗位", trigger: "change" }],
  },
});

// 新增
const add = () => {
  mainIndex = layer.open({
    type: 1,
    title: i18n.language === "zh-cn" ? "新增菜单" : "add menu",
    content: $("#saveOrUpdateDiv"),
    area: ["800px", "450px"],
    success: function (index) {
      //清空表单数据
      $("#dataFrm")[0].reset();
      $("input[name=spread][value='1']").prop("checked", false);
      $("input[name=spread][value='0']").prop("checked", true);
      $("input[name=available][value='1']").prop("checked", true);
      $("input[name=available][value='0']").prop("checked", false);
      $("#menuSelectDiv").removeClass("layui-show");
      url = $httpUrl + "/sel/addMenu";
    },
  });
};

// 修改分页数
const onChanSize = (e) => {
  data.queryForm.page = 1;
  data.queryForm.limit = e;
  getTableList();
};

// 修改分页
const onChanPage = (e) => {
  data.queryForm.page = e;
  getTableList();
};

// 删除
const del = (data) => {
  ElMessageBox.confirm(i18n.language === "zh-cn" ? "确认删除？" : "Confirm deletion?", i18n.language === "zh-cn" ? "提示" : "prompt").then(() => {
    $.post($httpUrl + "/sel/deleteMenu", { id: data.id }, function (res) {
      layer.msg(res.msg);
      menuTree.reload();
      getTableList();
    });
  });
};
// 编辑
const edit = (data) => {
  mainIndex = layer.open({
    type: 1,
    title: i18n.language === "zh-cn" ? "修改菜单" : "Modify",
    content: $("#saveOrUpdateDiv"),
    area: ["800px", "450px"],
    success: function (index) {
      form.val("dataFrm", data);
      url = $httpUrl + "/sel/updateMenu";
      //反选下拉树
      var pid = data.pid;
      var params = dtree.dataInit("menuTree", pid);
      //移除打开的样式
      $("#menuSelectDiv").removeClass("layui-show");
      //给下拉框的text框赋值
      $("#pid_str").val(params.context);
    },
  });
};
// 提交新增/编辑表单
let formRef = ref(null);
const submit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
    }
  });
};
// 获取表格数据
const getTableList = (params) => {
  data.loading = true;
  $axios
    .get("/sel/queryMenuAllList", {
      ...data.queryForm,
      ...params,
      id: id.value,
    })
    .then((res) => {
      data.loading = false;
      data.tableData = res.data.data.records;
      data.total = res.data.data.total;
    });
};

let id = ref();
const doQuery = (params) => {
  console.log("toMenuManager->doQuery->params", params);
  if (params.id) {
    id.value = params.id;
  }
  getList({ ...params, id: id.value });
};

const showType = (type) => {
  if (type == -1) return "系统";
  if (type == 0) return "云平台";
  if (type == 1) return "云产品";
  if (type == 2) return "云设备";
};
var $ = "";
var layer = "";
var form = "";
var table = "";
var dtree = "";
var mainIndex = "";
var url;
var menuTree = "";

onMounted(() => {
  layui
    .extend({
      dtree: "/layui_ext/dist/dtree",
    })
    .use(["jquery", "layer", "form", "table", "dtree"], function () {
      $ = layui.jquery;
      layer = layui.layer;
      form = layui.form;
      table = layui.table;
      dtree = layui.dtree;
      //初始化新增和修改页面的下拉树
      menuTree = dtree.render({
        elem: "#menuTree",
        dataStyle: "layuiStyle", //使用layui风格的数据格式
        response: { message: "msg", statusCode: 0 }, //修改response中返回数据的定义
        dataFormat: "list", //配置data的风格为list
        url: $httpUrl + "/sel/loadMenuMangerLeftTreeJson?spread=1", // 使用url加载（可与data加载同时存在）
        icon: "2",
        accordion: true,
      });
      $("#pid_div").on("click", function () {
        $(this).toggleClass("layui-form-selected");
        $("#menuSelectDiv").toggleClass("layui-show layui-anim layui-anim-upbit");
      });
      dtree.on("node(menuTree)", function (obj) {
        $("#pid_str").val(obj.param.context);
        $("#pid").val(obj.param.nodeId);
        $("#pid_div").toggleClass("layui-form-selected");
        $("#menuSelectDiv").toggleClass("layui-show layui-anim layui-anim-upbit");
      });
      //保存
      form.on("submit(doSubmit)", function (obj) {
        //序列化表单数据
        var params = $("#dataFrm").serialize();
        $.post(url, params, function (res) {
          if ((res.code = 200)) {
            layer.msg(res.msg);
            //关闭弹出层
            layer.close(mainIndex);
            menuTree.reload();
            console.log("toMenuManager->onMounted->menuTree->doSubmit->getList()");
            getList();
          } else {
            layer.msg(res.msg);
          }
        });
      });
    });
  // 获取表格数据
  getTableList({});
});
</script>

<style lang="scss" scoped>
.available1 {
  color: orangered;
}

.select-test {
  position: absolute;
  max-height: 500px;
  height: 350px;
  overflow: auto;
  width: 100%;
  z-index: 123;
  display: none;
  border: 1px solid silver;
  top: 42px;
}

.layui-show {
  display: block !important;
}

#menuToolBar {
  display: flex;
  justify-content: left;
  align-items: left;
  flex: 1;
  padding-left: 20px;
}

.layui-form-label {
  width: 110px;
}

.layui-input-block {
  margin-left: 140px;
}

@import "/src/assets/icon/index.css";
@import "/src/assets/icon/icon.css";
</style>
<style>
.layui-layer-loading {
  display: none !important;
}
</style>
